import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:ywn_app/contains/ThemeGlobal.dart';
import 'package:ywn_app/moudle/entity/Movie.dart';
import 'package:ywn_app/utils/LoadAnimationUtil.dart';
import 'package:ywn_app/widget/CustomerSwiper.dart';
import '../contains/ThemeGlobal.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _pullNet();
  }

  List list = [];
  final images = [
    "https://pic.rmb.bdstatic.com/baidu-rmb-video-cover-1/2020-4/1586341162134/162cc8271f45.jpg",
    "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1584420907120&di=9b105e924f631e4ecda6e8881f0be2e0&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201604%2F24%2F20160424121701_vuhja.thumb.700_0.jpeg",
    "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1584339075495&di=10d7992089fb75bb6f8fb4d69635e3ff&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F64%2F76%2F20300001349415131407760417677.jpg"
  ];

  void _pullNet() async {
    await http
        .get(
            'https://haokan.baidu.com/videoui/api/videorec?tab=yinyue&act=pcFeed&pd=pc&num=30')
        .then((http.Response response) {
      Map<String, dynamic> user = json.decode(response.body);
      setState(() {
        list = user['data']['response']['videos'];
      });
    });
  }

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Widget buildCtn() {
    return CustomScrollView(
      slivers: <Widget>[
        SliverToBoxAdapter(
          child: Container(
            padding: EdgeInsets.only(top: 5,bottom: 5),
            height: 120,
            child: CustomerSwiper(
              images: images,
            ),
          ),
        ),
        SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            mainAxisSpacing: 2,
            crossAxisSpacing: 2,
            crossAxisCount: 2,
          ),
          delegate: SliverChildBuilderDelegate(
            (c, i) => Movie(
              title: list[i]['title'],
              sourceName: list[i]['source_name'],
              posterSmall: list[i]['poster_small'],
              fmlike: list[i]['fmlike'],
              fmplaycnt: list[i]['fmplaycnt_2'],
              duration: list[i]['duration'],
              playUrl: list[i]['play_url'],
              id: list[i]['id'],
              publishTime: list[i]['publish_time'],
              fmplaycnt2: list[i]['fmplaycnt'],
            ),
            childCount: list.length,
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        backgroundColor: backgroundColor,
        appBar: AppBar(
          elevation: 0,
          title: Text('首页'),
          centerTitle: true,
        ),
        body: Padding(
          padding: EdgeInsets.all(5),
          child: SmartRefresher(
            controller: _refreshController,
            enablePullUp: true,
            child: buildCtn(),
            header: GifHeader1(),
            footer: GifFooter1(),
            /*header: WaterDropHeader(
            ),*/
            onRefresh: () async {
              await Future.delayed(Duration(milliseconds: 2000));
              _pullNet();
              if (mounted)
                setState(() {
                  print(mounted);
                });
              _refreshController.refreshCompleted();
              /* if(failed){
               _refreshController.refreshFailed();
              }*/
            },
            onLoading: () async {
              await Future.delayed(Duration(milliseconds: 2000));
              await http
                  .get(
                      'https://haokan.baidu.com/videoui/api/videorec?tab=yinyue&act=pcFeed&pd=pc&num=30')
                  .then((http.Response response) {
                Map<String, dynamic> user = json.decode(response.body);
                setState(() {
                  list += user['data']['response']['videos'];
                });
              });
              if (mounted) setState(() {});
              _refreshController.loadComplete();
            },
          ),
        ));
  }
}
